package com.game.modular.gameCore.drawCards.service.impl;

import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.game.modular.gameCore.drawCards.mapper.CoreDrawMapper;
import com.game.modular.gameCore.drawCards.domain.CoreDraw;
import com.game.modular.gameCore.drawCards.service.CoreDrawService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * (CoreDraw)表服务实现类
 *
 * @author cxy
 * @since 2024-08-07 16:22:01
 */
@Slf4j
@Service
public class CoreDrawServiceImpl extends ServiceImpl<CoreDrawMapper, CoreDraw> implements CoreDrawService {
    Cache<String, Map<String, CoreDraw>> cache = Caffeine.newBuilder().build();

    @PostConstruct
    private void init() {
        CoreDraw initSelect = CoreDraw.builder().build();
        List<CoreDraw> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存数据,数据量为:{}", list.size());
        cache.put(
                "coreDraw",
                list.stream().collect(Collectors.toMap(item -> item.getType() + "-" + item.getLv(), CoreDraw -> CoreDraw))
        );
        log.info("数据缓存完成");
    }

    public List<CoreDraw> listCache() {
        return new ArrayList<>(mapCache().values());
    }

    public Map<String, CoreDraw> mapCache() {
        Map<String, CoreDraw> values = cache.getIfPresent("coreDraw");
        if (Objects.isNull(values)) {
            throw new RuntimeException("数据为空");
        }
        return values;
    }

    public CoreDraw getCache(Integer type, Integer lv) {
        return mapCache().get(type + "-" + lv);
    }

    public CoreDraw draw(Integer type) {
        Long weight = 0L;
        List<CoreDraw> collect =
                listCache().stream().filter(item -> item.getType().equals(type)).collect(Collectors.toList());
        for (CoreDraw coreDraw : collect) {
            weight += coreDraw.getWeight();
        }
        // 随机数
        long index = ThreadLocalRandom.current().nextLong(0L, weight + 1);
        CoreDraw res = null;
        Map<String, CoreDraw> values = mapCache();

        for (CoreDraw level : collect) {
            String key = type + "-" + level.getLv();
            CoreDraw coreDraw = values.get(key);
            long levWeight = coreDraw.getWeight(); // 获取权重
            index -= levWeight;
            if (index < 0) {
                res = coreDraw;
                break;
            }
        }
        return res;
    }
}
